package com.atguigu.spzx.manager.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.spzx.manager.mapper.CategoryMapper;
import com.atguigu.spzx.model.entity.product.Category;
import jakarta.servlet.ReadListener;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Mahone
 */
@NoArgsConstructor
public class CategoryReadListener  extends AnalysisEventListener<Category> {

    List<Category> categories = new ArrayList<>();

    /**
     *     这边不能用自动注入，防止线程共享
      */
    private CategoryMapper categoryMapper;

    public CategoryReadListener(CategoryMapper categoryMapper) {
        this.categoryMapper = categoryMapper;
    }

    @Override
    public void invoke(Category category, AnalysisContext analysisContext) {
        categories.add(category);
        if (categories.size() >= 100) {
            System.out.println("每100条处理一次");
            categoryMapper.insertCategory(categories);
            categories.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        System.out.println("收尾");
        categoryMapper.insertCategory(categories);
    }
}
